package com.yupi.springbootinit.controller;

import cn.hutool.json.JSONUtil;
import jodd.util.ComparableComparator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
@RequestMapping("/queue")
@Slf4j
public class QueueController {
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @GetMapping("/add")
    public void add(String name){
        CompletableFuture.runAsync(()->{
          log.info("任务执行中："+name+"执行人："+Thread.currentThread().getName());
            try {
                Thread.sleep(6000000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            //这个参数是☞在哪个线程池中执行
        },threadPoolExecutor);
    }

    @GetMapping("/get")
    public String get(){
        Map<String,Object> map = new HashMap<>();
        //线程池中的队列长度
        int size = threadPoolExecutor.getQueue().size();
        map.put("线程池队列的长度",size);
        //获取线程池中的任务总数
        long taskCount = threadPoolExecutor.getTaskCount();
        map.put("线程池中的任务总数",taskCount);
        //已完成的线程数
        long completedTaskCount = threadPoolExecutor.getCompletedTaskCount();
        map.put("已完成的线程数",completedTaskCount);
        //正在执行的任务的线程数
        int activeCount = threadPoolExecutor.getActiveCount();
        map.put("在执行的任务的线程数",activeCount);
        return JSONUtil.toJsonStr(map);
    }
}
